<script setup lang="ts">
import { ElInput, ElMessage } from "element-plus";
import { ProSelect, ProForm } from "@/modules/package/form";
import useEnum from "@/hooks/useEnum";
import useForm from "@/hooks/useForm";
import ApiAdmin from "@/api/admin";
import regMenu from "@/utils/reg";

const emits = defineEmits<{
  success: [];
}>();

const props = defineProps<{
  source: Record<string, any>;
}>();

const formItems = [
  // {
  //   label: "头像",
  //   col: 24,
  //   children: {
  //     field: "avatar",
  //     type: Uploader,
  //     props: {
  //       listType: "picture-card",
  //     },
  //   },
  // },

  {
    label: "管理员",
    itemProps: {
      rules: { required: true, message: "请输入管理员" },
    },
    children: {
      field: "nickname",
      type: ElInput,
      props: {
        showWordLimit: true,
        maxlength: 20,
      },
    },
  },

  {
    label: "角色",
    itemProps: {
      rules: { required: true, message: "请选择角色" },
    },
    hidden: (model: any) => model?.id == 1,
    children: {
      field: "role",
      type: ProSelect,
      options: useEnum("EnumRoles")["list"],
    },
  },

  {
    label: "手机号",
    itemProps: {
      rules: [
        { required: true, message: "请输入手机号" },
        { pattern: regMenu.mobile, message: "手机号格式不正确" },
      ],
    },
    children: {
      field: "mobile",
      type: ElInput,
      props: {
        maxlength: 11,
      },
    },
  },

  {
    label: "密码",
    hidden: (model: any) => !!model?.id,
    itemProps: {
      rules: [
        { required: true, message: "请输入密码" },
        { pattern: regMenu.password, message: "密码由六位字母+数字组成" },
      ],
    },
    children: {
      field: "password",
      type: ElInput,
      props: {
        type: "password",
      },
    },
  },
];

const fetchKey = props.source
  ? props.source?.id
    ? "updateAdminUser"
    : "updateAdminUserById"
  : "addAdminUser";

// 提交数据
const { refForm, model, isFetching, submit, reset, onFetchResponse } = useForm(
  ApiAdmin[fetchKey],
  { defaultModel: { ...props.source } }
);

onFetchResponse(() => {
  ElMessage.success("操作成功！");
  emits("success");
});
</script>
<template>
  <ProForm
    ref="refForm"
    :col="24"
    :model="model"
    :loading="isFetching"
    :formItems="formItems"
    label-width="5em"
    label-position="left"
    @submit="submit"
    @reset="reset"
  />
</template>
